package eval

import (
	"fmt"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/zclconf/go-cty/cty"
)

func (ec *WrapperEvalContext) AttrValueAsString(attrs hcl.Attributes, key string) (*string, hcl.Diagnostics) {
	if attr, has := attrs[key]; has {
		if value, diags := attr.Expr.Value(ec.EvalContext); diags.HasErrors() {
			return nil, diags
		} else {
			return util.StringPtr(value.AsString()), nil
		}
	}
	return nil, nil
}

func (ec *WrapperEvalContext) AttrValueAsInt(attrs hcl.Attributes, key string) (*uint, hcl.Diagnostics) {
	if attr, has := attrs[key]; has {
		if value, diags := attr.Expr.Value(ec.EvalContext); diags.HasErrors() {
			return nil, diags
		} else {
			if value.Type() != cty.Number || !value.AsBigFloat().IsInt() {
				return nil, hcl.Diagnostics{
					&hcl.Diagnostic{
						Severity: hcl.DiagError,
						Summary:  "Not a integer",
						Detail:   fmt.Sprintf("Attribate %s expected a integer, but is %s", key, value.GoString()),
					},
				}
			}
			i, _ := value.AsBigFloat().Uint64()
			return util.UintPtr(uint(i)), nil
		}
	}
	return nil, nil
}

func (ec *WrapperEvalContext) AttrValueAsBoolean(attrs hcl.Attributes, key string) (*bool, hcl.Diagnostics) {
	if attr, has := attrs[key]; has {
		if value, diags := attr.Expr.Value(ec.EvalContext); diags.HasErrors() {
			return nil, diags
		} else {
			return util.BoolPtr(value.True()), nil
		}
	}
	return nil, nil
}
